# coding:utf-8
from typing import List

from fastapi import APIRouter, UploadFile, Form, Request, Security
from fastapi.params import File
from tortoise.expressions import Q

from app.admin.service.system.admin import AdminService
from app.admin.schemas.passport import AccountLogin
from app.admin.service.system.role import SystemRoleService
from app.common.enums import StatusEnum
from app.config.settings import settings
from app.core.response import response_fail, response_ok, Success
from app.core.auth import verify_password, create_access_token
from app.dependencies.verify import verify_token
from app.plugins.storage.storage_driver import StorageDriver

router = APIRouter()


@router.post("/login", summary="登录系统")
async def login(account: AccountLogin):
    """
    用户登陆
    :param account: username，password
    :return: jwt token
    """
    admin_service = AdminService()
    if account.username and account.password:
        # 查询条件
        query = Q()
        if account.username:
            query &= Q(username=account.username)
        # 账号密码登陆
        get_user = await admin_service.find(query)
        if not get_user:
            return response_fail(msg=f"用户{account.username}密码验证失败!")
        if not get_user.password:
            return response_fail(msg=f"用户{account.username}密码验证失败!")
        if not verify_password(account.password, get_user.password):
            return response_fail(msg=f"用户{account.username}密码验证失败!")
        if get_user.status != StatusEnum.normal:
            return response_fail(msg=f"用户{account.username}已被管理员禁用!")

        jwt_data = {
            "user_id": get_user.id,
            # "is_super": get_user.is_super,
            "username": get_user.username,
        }

        jwt_token = create_access_token(data=jwt_data)
        data = {"token": jwt_token, "expires_in": settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES * 60}
        # await write_access_log(req, get_user.pk, "通过用户名登陆了系统!")
        return Success(msg="登陆成功😄", data=data)


@router.get("/get_user_info", summary="查看角色菜单", dependencies=[Security(verify_token)])
async def get_user_info(request: Request):
    admin_id = request.state.admin_id
    role_ids = request.state.role_ids
    user_info = await AdminService().get_id(admin_id)
    info = await user_info.to_dict(exclude_fields=["password", "is_deleted"])
    if len(role_ids) == 0:
        return Success(data={})
    model_service = SystemRoleService()
    lists = await model_service.get_menu_by_role_id(role_ids=role_ids)
    info["role_ids"] = role_ids
    info["menu_ids"] = lists
    return Success(data=info)


# @router.post("/register", summary="注册用户")
# async def register(admin: AdminRegister):
#     """
#     创建用户
#     :param admin: AdminRegister
#     :return:
#     """
#     admin_service = AdminService()
#     # 过滤用户
#     if admin.password != admin.confirm_password:
#         return response_fail(msg="确认密码不一致")
#
#     get_user = await admin_service.find({"username": admin.username})
#     if get_user:
#         return response_fail(msg=f"用户名{admin.username}已经存在!")
#
#     # 创建用户
#     create_user = await admin_service.register(admin)
#     if not create_user:
#         return response_fail(msg=f"用户{admin.username}创建失败!")
#     # if admin.roles:
#     #     # 有分配角色
#     #     roles = await Role.filter(id__in=admin.roles, role_status=True)
#     #     await create_user.role.add(*roles)
#     return response_ok(msg=f"用户{admin.username}注册成功")


class UploadModel:
    pass


@router.post("/upload/file", summary="文件上传")
async def upload_file(file: UploadFile, folder_id: int = Form(0), folder: str = Form(None)):
    """单文件上传"""
    result = await StorageDriver.upload(file, folder)

    creat_file = await UploadModel.create(
        channel=1,
        folder_id=folder_id,
        uid=1,
        type=result['type'],
        storage=result['storage'],
        name=result['name'],
        url=result['url'],
        ext=result['ext'],
        size=result['size']
    )
    return creat_file


# multiple
@router.post("/upload/multiple", summary="多文件上传")
async def upload_multiple(files: List[UploadFile] = File(), folder_id: int = Form(0), folder: str = Form(None)):
    """多文件上传"""
    results = []
    try:
        # 保存上传的文件到本地，并记录信息
        for uploaded_file in files:
            try:
                result = await StorageDriver.upload(uploaded_file, folder)

                creat_file = await UploadModel.create(
                    channel=1,
                    folder_id=folder_id,
                    uid=1,
                    type=result['type'],
                    storage=result['storage'],
                    name=result['name'],
                    url=result['url'],
                    ext=result['ext'],
                    size=result['size']
                )
                results.append({"file_name": uploaded_file.filename, "path": creat_file.url})
            except Exception as e:
                results.append({"file_name": uploaded_file.filename, "status": f"Failed to upload: {str(e)}"})
    finally:
        print(results)
    return results
